<?php
namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

use app\admin\Controller;
use think\Config;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;

class HotelTimePrice extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function filter(&$map)
    {
        if ($this->request->param("hotel_id")) {
            $map['hotel_id'] = ["like", "%" . $this->request->param("hotel_id") . "%"];
        }
        if ($this->request->param("hotel_location")) {
            $map['hotel_location'] = ["like", "%" . $this->request->param("hotel_location") . "%"];
        }
        if ($this->request->param("remark")) {
            $map['remark'] = ["like", "%" . $this->request->param("remark") . "%"];
        }
    }

    /**
     * 首页
     */
    public function index()
    {
        $data = input();
        // 查询条件
        if ($data['room_type_id']){
            $room_type_id = Db::name('room_hotel_number')->where('room_type_id',$data['room_type_id'])->field('hotel_id')->select();
            if ($room_type_id){
                $roomTypeId = '';
                foreach ($room_type_id as $index => $item) {
                    $roomTypeId .= $item['hotel_id'].',';
                }
                $roomTypeId = rtrim($roomTypeId,',');
                $map['hotel_id'] = ['in', $roomTypeId];
            }
        }
        if ($data['hotel_id']){
            // 从酒店获取酒店id
            $hotelIds = Db::name('hotel')->where('hotel_name','like',"%{$data['hotel_id']}%")->field('id')->select();
            if ($hotelIds) {
                $hotel_id = '';
                foreach ($hotelIds as $index => $hotelId) {
                    $hotel_id .= $hotelId['id'] . ',';
                }
                $hotel_id = rtrim($hotel_id, ',');
                if (empty($map['hotel_id'])){
                    $map['hotel_id'] = ['in',$hotel_id];
                }else{
                    $hotelIds = explode(',',$hotel_id);
                    $hotel_id = explode(',',$map['hotel_id'][1]);

                    $hotel_ids = '';
                    foreach ($hotelIds as $index => $hotelId) {
                        if (in_array($hotelId,$hotel_id)){
                            $hotel_ids .= $hotelId.',';
                        }
                    }
                    $map['hotel_id'] = ['in', rtrim($hotel_ids,',')];
                }
            }
        }
        if ($data['hotel_location']){
            $map['hotel_location'] = ['like',"%{$data['hotel_location']}%"];
        }
        if ($data['start_time']){
            $map['start_time'] = $data['start_time'];
        }
        if ($data['end_time']){
            $map['end_time'] = $data['end_time'];
        }
        if ($data['remark']){
            $map['remark'] = ['like',"%{$data['remark']}%"];
        }
        if ($data['include_breakfast']){
            $mapr['include_breakfast'] = $data['include_breakfast'];
            $room_pr = Db::name('hotel_room_price')->where($mapr)->field('hotel_time_price_id')->select();
            foreach($room_pr as $k => $v) {
                $tpr_id[] = $v['hotel_time_price_id'];
            }
            $map['id'] = ['in',$tpr_id];
        }
        if ($data['create_time']){
            $start_time = "{$data['create_time']} 0:0:0";
            $end_time = "{$data['create_time']} 23:59:59";
            $map['create_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        if (isset($data['enable_status'])){
            $map['enable_status'] = ['like',"%{$data['enable_status']}%"];
        }
        // 查询所有
        if ($this::$isdelete){
            $map['isdelete'] = 1;
        }else{
            $map['isdelete'] = 0;
        }
        $listRows = $this->request->param('numPerPage') ? 20: Config::get("paginate.list_rows");
        $list = Db::name('hotel_time_price')->where($map)->order('id','desc')->paginate($listRows, false, ['query' => $this->request->get()]);
        $listData = $list->toArray()['data'];
        //var_dump(Db::name('hotel_time_price')->getLastSql());
        if ($listData){
            foreach ($listData as $index => $listDatum) {
                $listData[$index]['room_data'] = self::getRoomPrices($listDatum);
            }
        }
        $hotel_room_type = Db::name('hotel_room_type')->where('isdelete',0)->select();
        $count = $list->count();

        $this->view->assign('list',$list);
        $this->view->assign('searchCondition',$data);
        $this->view->assign('listData', $listData);
        $this->view->assign('count',$count);
        $this->view->assign('page',$list->render());
        $this->view->assign('hotel_room_type',$hotel_room_type);
        return $this->view->fetch();
    }

    /*
     *启用与禁用功能
     */
    public function enable(){
        $data = input();

        $dataInfo = Db::name('hotel_time_price')->find($data['id']);
        $enable_status = $data['status'] ? 0 : 1;
        $update['enable_status']=$enable_status;
        $result = Db::name('hotel_time_price')->where('id',$data['id'])->update($update);
        return json(['code' => 1,'msg' => '修改成功','data' => $result]);

    }

    /**
     * 添加
     */
    public function add(Request $request)
    {
        if ($request->isPost()){

            $postData = $request->post(); //获取数据

            $room_names = [];
            $room_prices = [];
            $include_breakfasts = [];

            //获取酒店房型数据
            foreach ($postData as $k => $v){
                $temp_name = substr($k,0,10);
                $temp_room_price = substr($k,0,11);
                $temp_include_breakfast = substr($k,0,18);

                if($temp_name == 'room_name_'){
                    //房型名称
                    if(!empty($v)){
                        if(in_array($v,$room_names)){
                            return ajax_return_error('所添加的房型存在重复');
                        }
                        $room_names[] = $v;
                    }else{
                        return ajax_return_error('房型名称不能为空');
                    }
                }
                if($temp_room_price == 'room_price_'){
                    //房型价格
                    if(is_numeric($v)){
                        $room_prices[] = $v;
                    }else{
                        return ajax_return_error('房型价格格式有误');
                    }
                }
                if($temp_include_breakfast == 'include_breakfast_'){
                    //是否包含早餐
                    if($v == 1 || $v == 0){
                        $include_breakfasts[] = $v;
                    }else{
                        return ajax_return_error('请选择‘是’或者‘否’');
                    }
                }
            }

            // 验证数据
            $rule = [
                'hotel_id'=>'require',
                'end_time'=>'require',
                'start_time'=>'require',
            ];
            $message = [
                'hotel_id.require' => '酒店名称不能为空',
                'end_time.require' => '结束时间不能为空',
                'start_time.require' => '开始时间不能为空',
            ];
            $validate = new Validate($rule,$message);
            $result = $validate->check($postData);
            if (!$result){
                return ajax_return_adv_error($validate->getError());
            }
            unset($postData['id']);
            if (empty($postData['hotel_location'])){
                $postData['hotel_location'] = Db::name('hotel')->where('id',$postData['hotel_id'])->value('hotel_location');
            }
            $postData['create_time'] = time();
            if ($postData['start_time'] > $postData['end_time']){
                return ajax_return_adv_error('结算价格的开始时间不能大于结束时间');
            }
            // 开始日期与结算日期
            $tian = round((strtotime($postData['end_time'])-strtotime($postData['start_time']))/3600/24);
            // 把入住日期与退房日期的相差天数
            $date = [$postData['start_time']];
            for ($i=1; $i<= $tian; $i++){
                array_push($date,date("Y-m-d",strtotime("+{$i} day", strtotime($postData['start_time']))));//添加的
            }
            foreach ($date as $index => $item) {
                $map['start_time'] = ['<=',$item];
                $map['end_time'] = ['>=',$item];
                $find =  Db::name('hotel_time_price')->where('hotel_id',$postData['hotel_id'])
                                                            ->where($map)->find();
                if ($find){
                    $hotelName = Db::name('hotel')->where('id',$postData['hotel_id'])->value('hotel_name');
                    return ajax_return_adv_error("酒店名称为:{$hotelName},已存在{$item}的结算价格!");
                }
            }

            Db::startTrans();
            try{
                $addId = Db::name('hotel_time_price')->strict(false)->insertGetId($postData);
                if ($addId){
                    if(count($room_names)>0){
                        foreach ($room_names as $kk => $vv){
                            $insert_data = [
                                'hotel_time_price_id' => $addId,
                                'room_type_id' => $vv,
                                'room_price' => $room_prices[$kk],
                                'hotel_id' => $postData['hotel_id'],
                                'create_time' => time(),
                                'include_breakfast' => $include_breakfasts[$kk],
                            ];
                            Db::name('hotel_room_price')->strict(false)->insert($insert_data);
                        }
                    }
                    return ajax_return_adv('添加成功');
                }else{
                    return ajax_return_adv_error('添加失败');
                }
            }catch (\Exception $e){
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }

        }else{

            // 查询所有的酒店
            $hotel = Db::name('hotel')->where('isdelete', 0)->select();
            $this->view->assign('hotel',$hotel);
            return $this->view->fetch();
        }
    }

    /**
     * 编辑
     */
    public function edit(Request $request)
    {
        if ($request->isPost()){
            $postData = $request->post();
            if (empty($postData['hotel_location'])){
                $postData['hotel_location'] = Db::name('hotel')->where('id',$postData['hotel_id'])->value('hotel_location');
            }
            $updateCount = Db::name('hotel_time_price')->strict(false)->update($postData);
            if ($updateCount){
                return ajax_return_adv('更新成功');
            }else{
                return ajax_return_adv_error('更新失败');
            }
        }else{
            $data = input();
            if (!$data['id']) {
                return ajax_return_adv_error('缺少参数');
            }
            // 查找该结算价格信息
            $vo = Db::name('hotel_time_price')->where('id',$data['id'])->find();
            // 查询所有的酒店
            $hotel = Db::name('hotel')->where('isdelete', 0)->select();
            $this->view->assign('hotel',$hotel);
            $this->view->assign('vo',$vo);
            return $this->view->fetch();
        }
    }

    /**
     * 导出数据到excel
     */
    public function get_excel(Request $request)
    {
        $data = input();
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel,'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l+65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j].$letter[$k];
            }
        }
        $tableHeader = ['id','酒店名称','酒店位置','开始时间','结束时间','备注','添加时间','是否删除','数据汇总备注','结算状态','房型--房价'];
        $li_length = count($letter);//设置单元格的宽度
        for ($li=0;$li<$li_length;$li++){
            switch ($letter[$li]){
                case 'A':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(10);break;
                case 'B':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(50);break;
                case 'C':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(50);break;
                case 'D':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'E':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'G':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'H':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'I':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                case 'J':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(20);break;
                case 'K':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(200);break;
                case 'L':$export_sheet->getColumnDimension("$letter[$li]")->setWidth(18);break;
                default:
                    $export_sheet->getColumnDimension("$letter[$li]")->setWidth(25);
            }
        }
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++){
            $export_sheet->setCellValue("$letter[$i]1","$tableHeader[$i]");
        }
        if($this::$isdelete){
            $map['isdelete']=1;
        }else{
            $map['isdelete']=0;
        }
        if ($data['room_type_id']){
            $room_type_id = Db::name('room_hotel_number')->where('room_type_id',$data['room_type_id'])->field('hotel_id')->select();
            if ($room_type_id){
                $roomTypeId = '';
                foreach ($room_type_id as $index => $item) {
                    $roomTypeId .= $item['hotel_id'].',';
                }
                $roomTypeId = rtrim($roomTypeId,',');
                $map['hotel_id'] = ['in', $roomTypeId];
            }
        }
        if ($data['hotel_id']){
            // 从酒店获取酒店id
            $hotelIds = Db::name('hotel')->where('hotel_name','like',"%{$data['hotel_id']}%")->field('id')->select();
            if ($hotelIds) {
                $hotel_id = '';
                foreach ($hotelIds as $index => $hotelId) {
                    $hotel_id .= $hotelId['id'] . ',';
                }
                $hotel_id = rtrim($hotel_id, ',');
                if (empty($map['hotel_id'])){
                    $map['hotel_id'] = ['in',$hotel_id];
                }else{
                    $hotelIds = explode(',',$hotel_id);
                    $hotel_id = explode(',',$map['hotel_id'][1]);

                    $hotel_ids = '';
                    foreach ($hotelIds as $index => $hotelId) {
                        if (in_array($hotelId,$hotel_id)){
                            $hotel_ids .= $hotelId.',';
                        }
                    }
                    $map['hotel_id'] = ['in', rtrim($hotel_ids,',')];
                }
            }
        }
        if ($data['hotel_location']){
            $map['hotel_location'] = ['like',"%{$data['hotel_location']}%"];
        }
        if ($data['start_time']){
            $map['start_time'] = $data['start_time'];
        }
        if ($data['end_time']){
            $map['end_time'] = $data['end_time'];
        }
        if ($data['remark']){
            $map['remark'] = ['like',"%{$data['remark']}%"];
        }
        if ($data['create_time']){
            $start_time = "{$data['create_time']} 0:0:0";
            $end_time = "{$data['create_time']} 23:59:59";
            $map['create_time'] = ['between',[strtotime($start_time),strtotime($end_time)]];
        }
        switch ($data['settlement_status']){
            case 1: $map['settlement_status'] = 1; break;
            case 2: $map['settlement_status'] = 2; break;
            case 3: $map['settlement_status'] = 3; break;
            default: unset($data['settlement_status']);
        }
        //选择导出数据
        if ($data['id']){
            $id = implode($data['id'],',');
            $map['id'] = ['in',$id];
        }

        //查询要填充表格数据
        $list = Db::name('hotel_time_price')
            ->where($map)
            ->order("id desc")
            ->select();

//        dump($list);die;
        //字段转换
        foreach ($list as $lk=>$lv) {
            $list[$lk]['create_time'] = empty($lv['create_time']) ? '' : date('Y-m-d H:i:s', $lv['create_time']);
            $list[$lk]['hotel_id'] = empty($lv['hotel_id']) ? '': Db::name('hotel')->where('id',$lv['hotel_id'])->value('hotel_name') ;
            $list[$lk]['isdelete'] = empty($lv['isdelete']) ?  '未删除' : '已删除';
            $priceList = self::getRoomPrices($lv);
            $str = '';
            if ($priceList['room_type'] != '尚未有房型'){
                foreach ($priceList as $index => $item) {
                    $str .= "{$item['room_type']} --- {$item['price']},";
                }
            }
            $list[$lk]['price_list'] = rtrim($str,',');
            switch ($lv['settlement_status']){
                case 1: $list[$lk]['settlement_status'] = '申请结算'; break;
                case 2: $list[$lk]['settlement_status'] = '未结算'; break;
                case 3: $list[$lk]['settlement_status'] = '已结算'; break;
                default: $list[$lk]['settlement_status']='申请结算';
            }
        }
        //定义table键
        if (!empty($list)){
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk=>$tv){
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++){
                    $export_sheet->setCellValue("$letter[$i]".$tk,$tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis',time())."酒店管理-结算价格数据.xls";
        $fileName = iconv('utf-8','gb2312',$fileName);
        ob_end_clean();
        if ($request->isGet()){
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename='.$fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        }else{
            // 保存文件到服务器上
            $path = ROOT_PATH."public/excel";
            // 判断文件是否存在
            if (!file_exists($path)){
                mkdir($path,0777,true);
            }
            $fileName = iconv('gb2312','utf-8',$fileName);
            $file = $path."/{$fileName}";
            $writer->save($file);
            $url =$request->domain()."/excel/{$fileName}";
            return ajax_return_adv($url,'','','','','',5);
        }
    }
    
    /**
     * 获取酒店房型房价
     */
    public static function getRoomPrices($data)
    {
        $map = [];
        // 根据结算id查找
        $hotel_room_price = Db::name('hotel_room_price')->where('hotel_time_price_id',$data['id'])->select();
        if (!$hotel_room_price || !$data['id']){
            $price = 0;
            $map[] = [
                'room_type' => '尚未有房型',
                'price' => '尚未有价格',
                'include_breakfast' => null
            ];
            return $map;
        }
        $priceStr = '';
        foreach ($hotel_room_price as $index => $item) {
            $type_name = Db::name('hotel_room_type')->where('id',$item['room_type_id'])->value('room_name');
            if ($type_name) {
                $priceStr .= "{$type_name} -- {$item['room_price']},";
                $map[] = [
                    'room_type' => $type_name,
                    'price' => $item['room_price'],
                    'include_breakfast' => $item['include_breakfast']
                ];
            }else{
                $priceStr .= "不存在房型 -- {$item['room_price']},";
                $map[] = [
                    'room_type' => '房型已被删',
                    'price' => $item['room_price'],
                    'include_breakfast' => $item['include_breakfast']
                ];
            }
        }
        $priceStr = rtrim($priceStr,',');
        return $map;
    }
}
